{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Pandas 分位数统计 - quantile()\n",
        "\n",
        "本教程详细介绍如何使用 `quantile()` 方法计算分位数和百分位数。\n",
        "\n",
        "## 目录\n",
        "1. quantile() 基础用法\n",
        "2. 单个分位数\n",
        "3. 多个分位数\n",
        "4. 常用的百分位数\n",
        "5. 分位数的应用\n",
        "6. 与describe()的对比\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 导入库\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "import numpy as np\n",
        "import warnings\n",
        "warnings.filterwarnings('ignore')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 1. quantile() 基础用法\n",
        "\n",
        "### 方法说明\n",
        "\n",
        "`quantile()` 方法用于计算分位数（百分位数）。\n",
        "\n",
        "**语法:**\n",
        "```python\n",
        "df.quantile(q=0.5, axis=0, numeric_only=True, interpolation='linear')\n",
        "```\n",
        "\n",
        "**主要参数:**\n",
        "- `q`: 分位数，0-1之间的浮点数或列表，默认0.5（中位数）\n",
        "- `axis`: 0(按列) 或 1(按行)，默认 0\n",
        "- `numeric_only`: 是否只计算数值型列，默认 True\n",
        "- `interpolation`: 插值方法，'linear', 'lower', 'higher', 'midpoint', 'nearest'\n",
        "\n",
        "**常用分位数:**\n",
        "- `q=0.25`: 第一四分位数（Q1）\n",
        "- `q=0.5`: 中位数（Q2）\n",
        "- `q=0.75`: 第三四分位数（Q3）\n",
        "- `q=0.1, 0.9`: 十分位数\n",
        "- `q=0.01, 0.99`: 百分位数\n",
        "\n",
        "**特点:**\n",
        "- ✅ 支持单个或多个分位数计算\n",
        "- ✅ 默认返回中位数（50%分位数）\n",
        "- ✅ 适用于数值型数据\n",
        "- ✅ 可以设置插值方法\n",
        "\n",
        "**适用场景:** 了解数据分布、检测异常值、数据分析\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例1: 创建示例数据\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "np.random.seed(42)\n",
        "df = pd.DataFrame({\n",
        "    '年龄': np.random.randint(20, 60, 100),\n",
        "    '工资': np.random.normal(8000, 2000, 100),\n",
        "    '身高': np.random.normal(170, 10, 100),\n",
        "    '体重': np.random.normal(70, 10, 100)\n",
        "})\n",
        "\n",
        "print(\"原始数据 (前10行):\")\n",
        "print(df.head(10))\n",
        "print(\"\\n数据形状:\", df.shape)\n",
        "print(\"\\n数据类型:\")\n",
        "print(df.dtypes)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 2. 单个分位数\n",
        "\n",
        "### 示例2: 计算中位数（默认）\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 默认计算中位数（50%分位数）\n",
        "print(\"中位数（默认 q=0.5）:\")\n",
        "print(df.quantile())\n",
        "print(\"\\n或明确指定:\")\n",
        "print(df.quantile(0.5))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例3: 计算单个列的分位数\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 计算工资的中位数\n",
        "print(\"工资中位数:\", df['工资'].quantile())\n",
        "print(\"工资中位数（明确指定）:\", df['工资'].quantile(0.5))\n",
        "print(\"工资第一四分位数:\", df['工资'].quantile(0.25))\n",
        "print(\"工资第三四分位数:\", df['工资'].quantile(0.75))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 3. 多个分位数\n",
        "\n",
        "### 示例4: 计算多个分位数\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 计算多个分位数\n",
        "quantiles = [0.25, 0.5, 0.75]\n",
        "print(\"四分位数 (25%, 50%, 75%):\")\n",
        "print(df.quantile(quantiles))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 4. 常用的百分位数\n",
        "\n",
        "### 示例5: 计算常用百分位数\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 计算常用百分位数\n",
        "percentiles = [0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99]\n",
        "print(\"常用百分位数:\")\n",
        "print(df['工资'].quantile(percentiles))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例6: 插值方法\n",
        "\n",
        "`interpolation` 参数控制分位数的计算方法。\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 不同的插值方法\n",
        "data = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n",
        "print(\"原始数据:\", data.values)\n",
        "print(\"\\n不同插值方法的0.25分位数:\")\n",
        "print(\"linear (线性插值):\", data.quantile(0.25, interpolation='linear'))\n",
        "print(\"lower (下取整):\", data.quantile(0.25, interpolation='lower'))\n",
        "print(\"higher (上取整):\", data.quantile(0.25, interpolation='higher'))\n",
        "print(\"midpoint (中点):\", data.quantile(0.25, interpolation='midpoint'))\n",
        "print(\"nearest (最近):\", data.quantile(0.25, interpolation='nearest'))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 5. 分位数的应用\n",
        "\n",
        "### 示例7: 使用IQR检测异常值\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 使用IQR（四分位距）方法检测异常值\n",
        "Q1 = df['工资'].quantile(0.25)\n",
        "Q3 = df['工资'].quantile(0.75)\n",
        "IQR = Q3 - Q1\n",
        "lower_bound = Q1 - 1.5 * IQR\n",
        "upper_bound = Q3 + 1.5 * IQR\n",
        "\n",
        "print(f\"工资数据:\")\n",
        "print(f\"Q1 (25%): {Q1:.2f}\")\n",
        "print(f\"Q3 (75%): {Q3:.2f}\")\n",
        "print(f\"IQR: {IQR:.2f}\")\n",
        "print(f\"异常值下界: {lower_bound:.2f}\")\n",
        "print(f\"异常值上界: {upper_bound:.2f}\")\n",
        "\n",
        "outliers = df[(df['工资'] < lower_bound) | (df['工资'] > upper_bound)]\n",
        "print(f\"\\n异常值数量: {len(outliers)}\")\n",
        "if len(outliers) > 0:\n",
        "    print(\"异常值:\")\n",
        "    print(outliers[['工资']].head(10))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例8: 按分位数分组\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 根据工资分位数将数据分组\n",
        "df['工资等级'] = pd.cut(df['工资'], \n",
        "                      bins=[df['工资'].min()-1, \n",
        "                            df['工资'].quantile(0.33),\n",
        "                            df['工资'].quantile(0.67),\n",
        "                            df['工资'].max()+1],\n",
        "                      labels=['低', '中', '高'])\n",
        "print(\"按工资分位数分组:\")\n",
        "print(df[['工资', '工资等级']].head(20))\n",
        "print(\"\\n各等级统计:\")\n",
        "print(df['工资等级'].value_counts())\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 6. 与describe()的对比\n",
        "\n",
        "### 示例9: quantile() vs describe()\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# describe()自动计算25%, 50%, 75%分位数\n",
        "print(\"describe()方法:\")\n",
        "print(df['工资'].describe())\n",
        "print(\"\\nquantile()方法计算相同分位数:\")\n",
        "print(df['工资'].quantile([0.25, 0.5, 0.75]))\n",
        "print(\"\\n两者结果一致（除精度差异外）\")\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 总结\n",
        "\n",
        "**quantile() 方法的主要用途:**\n",
        "1. ✅ **分位数计算**: 计算任意分位数（0-1之间）\n",
        "2. ✅ **中位数计算**: 计算中位数（50%分位数）\n",
        "3. ✅ **四分位数**: 计算Q1、Q2、Q3\n",
        "4. ✅ **异常值检测**: 使用IQR方法\n",
        "5. ✅ **数据分组**: 根据分位数分组\n",
        "\n",
        "**最佳实践:**\n",
        "- 使用 `quantile(0.5)` 计算中位数（稳健的平均值）\n",
        "- 使用 `quantile([0.25, 0.5, 0.75])` 计算四分位数\n",
        "- 使用IQR方法检测异常值\n",
        "- 根据业务需求选择合适的分位数\n",
        "- 注意插值方法的选择（默认linear即可）\n"
      ]
    }
  ],
  "metadata": {
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}
